package com.handu.luna.boss.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.SecKillGroupBuy;
import com.handu.luna.core.domain.promotion.SecKillGroupBuyGoods;
import com.handu.luna.core.domain.searchVo.GoodsSearch;
import com.handu.luna.core.domain.support.FileUploadSupport;
import com.handu.luna.core.domain.support.FileUploadSupport.FileType;

@Controller
@RequestMapping("/promotion/seckillgroupbuygoods/*")
public class SecKillGroupBuyGoodsController extends BaseController{
	
	@RequestMapping(value = {"index/{secKillGroupBuyId}","/",""})
    public BossModel index(@PathVariable int secKillGroupBuyId,String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if(viewState == null || viewState.equals("")){
			return createModel("promotion/seckillgroupbuygoods/index")
					.add("seckillgroupbuygoodsPage",context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyId(secKillGroupBuyId, pageable))
					.add("viewState", "")
					.add("secKillGroupBuyId", secKillGroupBuyId);

		}else{
			return createModel("promotion/seckillgroupbuygoods/index")
					.add("seckillgroupbuygoodsPage",context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyId(secKillGroupBuyId, pageable))
					.add("viewState", viewState)
					.add("secKillGroupBuyId", secKillGroupBuyId);
		}
	}
	
	
	@RequestMapping(value="add/{secKillGroupBuyId}")
	public BossModel add(@PathVariable String secKillGroupBuyId){

		return createModel("promotion/seckillgroupbuygoods/addinfo").add("goodsSearch", new GoodsSearch())
				.add("secKillGroupBuyId", secKillGroupBuyId)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll());
	}
	
	@RequestMapping(value="edit/{secKillGroupBuyId}/{id}")
	public BossModel add(@PathVariable String secKillGroupBuyId,@PathVariable long id){

		return createModel("promotion/seckillgroupbuygoods/edit").add("skgbgood", context.getSecKillGroupBuyGoodsRepository().findOne(id))
				.add("secKillGroupBuyId", secKillGroupBuyId);
	}
	
	
	/**
	 * 查询商品展示(post提交查询)
	 * @param pageable
	 * @param salesPromotionId
	 * @param goodsSearch
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "list/{secKillGroupBuyId}",method=RequestMethod.POST)
	public BossModel list(@PathVariable int secKillGroupBuyId,GoodsSearch goodsSearch,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable)throws UnsupportedEncodingException {

		
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(goodsSearch),pageable);
		for (Goods good :goodsList) {
			List<SecKillGroupBuyGoods>skgbgood = context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyIdAndGoodsId(secKillGroupBuyId, good.getId());
			SecKillGroupBuy skgb = context.getSecKillGroupBuyRepository().findOne((long)secKillGroupBuyId);
			if(skgbgood.isEmpty()){
				good.setSeckillgroupbuy(0);
				good.setSeckillgroupbuyNumber(skgb.getSecKillGroupBuyNumber());
			}else{
				good.setSeckillgroupbuy(1);
				good.setSeckillgroupbuyPrice(skgbgood.get(0).getGoodsPrice());
				good.setSeckillgroupbuyNumber(skgbgood.get(0).getGoodsNumber());
			}
		}
		
		return createModel("promotion/seckillgroupbuygoods/info").add("goodsPage",goodsList)
				.add("goodsSearch", goodsSearch)
				.add("secKillGroupBuyId", secKillGroupBuyId)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
				.add("viewState", Base64.getEncoder().encodeToString(JSONObject.fromObject(goodsSearch).toString().getBytes("UTF-8")));
			
	}
	
	/**
	 * 查询商品展示(带参数翻页调用)
	 * @param pageable
	 * @param salesPromotionId
	 * @param viewState
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "list/{secKillGroupBuyId}",method=RequestMethod.GET)
	public BossModel list(String viewState,@PathVariable int secKillGroupBuyId,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable)throws UnsupportedEncodingException {

		GoodsSearch search;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), GoodsSearch.class);
		}else{
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search),pageable);
		for (Goods good :goodsList) {
			List<SecKillGroupBuyGoods>skgbgood = context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyIdAndGoodsId(secKillGroupBuyId, good.getId());
			SecKillGroupBuy skgb = context.getSecKillGroupBuyRepository().findOne((long)secKillGroupBuyId);
			if(skgbgood.isEmpty()){
				good.setSeckillgroupbuy(0);
				good.setSeckillgroupbuyNumber(skgb.getSecKillGroupBuyNumber());
			}else{
				good.setSeckillgroupbuy(1);
				good.setSeckillgroupbuyPrice(skgbgood.get(0).getGoodsPrice());
				good.setSeckillgroupbuyNumber(skgbgood.get(0).getGoodsNumber());
			}
		}
		if(viewState != null && !viewState.trim().equals("")){
			return createModel("promotion/seckillgroupbuygoods/info").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("secKillGroupBuyId", secKillGroupBuyId)
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", context.getCategoryRepository().findAll())
					.add("viewState", viewState);
		}else{
			return createModel("promotion/seckillgroupbuygoods/info").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("secKillGroupBuyId", secKillGroupBuyId)
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", context.getCategoryRepository().findAll())
					.add("viewState", "");
		}
			
	}
	
	@RequestMapping(value="save/{secKillGroupBuyId}",method = RequestMethod.POST)
	@InitBinder(value={"goodsPrice","goodsNumber"})
	public BossModel save(@Valid @ModelAttribute("skgbgood") final SecKillGroupBuyGoods skgbgood,@PathVariable int secKillGroupBuyId,final BindingResult bindingResult, RedirectAttributes redirectAttributes, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){

		String messagePrefix = skgbgood.getSucessFlashMessage();
		context.getSecKillGroupBuyGoodsRepository().save(skgbgood);
		return createModel("promotion/seckillgroupbuygoods/index")
				.add("seckillgroupbuygoodsPage",context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyId(secKillGroupBuyId, pageable))
				.add("viewState", "")
				.add("secKillGroupBuyId", secKillGroupBuyId)
				.add("message", messagePrefix);
	}
	
	@RequestMapping(value="ajaxsave",method = RequestMethod.POST)
	public BossModel save(String viewState,long id,int number, BigDecimal price, int skgbid, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException{
		//List<SalesPromotionGoods> goodsCheck = context.getSalesPromotionGoodsRepository().findBySalesPromotionIdAndGoodsId(spid, id);
		
		List<Goods> goodsCheckDelete = context.getGoodsRepository().findUnTrash(id);
		if(!goodsCheckDelete.isEmpty()){
			SecKillGroupBuyGoods skgbgoods = new SecKillGroupBuyGoods();
			skgbgoods.setSecKillGroupBuyId(skgbid);
			skgbgoods.setGoodsPrice(price);
			skgbgoods.setGoodsNumber(number);
			skgbgoods.setGoodsId(id);
			context.getSecKillGroupBuyGoodsRepository().save(skgbgoods);
		}	

		GoodsSearch search;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), GoodsSearch.class);
		}else{
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search),pageable);
		for (Goods good :goodsList) {
			List<SecKillGroupBuyGoods>skgbgood = context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyIdAndGoodsId(skgbid, good.getId());
			SecKillGroupBuy skgb = context.getSecKillGroupBuyRepository().findOne((long)skgbid);
			if(skgbgood.isEmpty()){
				good.setSeckillgroupbuy(0);
				good.setSeckillgroupbuyNumber(skgb.getSecKillGroupBuyNumber());
			}else{
				good.setSeckillgroupbuy(1);
				good.setSeckillgroupbuyPrice(skgbgood.get(0).getGoodsPrice());
				good.setSeckillgroupbuyNumber(skgbgood.get(0).getGoodsNumber());
			}
		}
		if(viewState != null && !viewState.trim().equals("")){
			return createModel("promotion/seckillgroupbuygoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("secKillGroupBuyId", skgbid)
					.add("viewState", viewState);
		}else{
			return createModel("promotion/seckillgroupbuygoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("secKillGroupBuyId", skgbid)
					.add("viewState", "");
		}
	}
	
	//判断商品是否已存在正在进行和即将开始的活动中
	@RequestMapping(value = "checkGood", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody String checkGood(long id) {

		//根据添加的商品ID判断该商品是否已经在活动中
		SecKillGroupBuy current = context.getSecKillGroupBuyGoodsRepository().findCurrentSecKillGroupBuyByGoodsId(id, new Date());
		SecKillGroupBuy unActivated = context.getSecKillGroupBuyGoodsRepository().findUnActivatedSecKillGroupBuyByGoodsId(id, new Date());
		if(current != null || unActivated != null){
			return "1";
		}else{
			return "0";
		}
    }
	
	@RequestMapping(value="uploadgoods/{secKillGroupBuyId}",method= RequestMethod.POST)
	public BossModel uploadgoods(@PathVariable int secKillGroupBuyId,@RequestParam("goodsFile") MultipartFile goodsFile, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws FileNotFoundException, IOException{
		if(!goodsFile.getOriginalFilename().equals("")){
			String fileName[] = goodsFile.getOriginalFilename().split("\\.");
			if(fileName[1].equals("xls")){
				
	            String fileUrl = FileUploadSupport.uploadFile(goodsFile.getInputStream(), goodsFile.getOriginalFilename(), FileType.XLS);
				
				HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(fileUrl));
				HSSFSheet sheet = wb.getSheetAt(0);
				//迭代行
				for (Iterator<Row> iter = (Iterator<Row>) sheet.rowIterator(); iter.hasNext();) {
				        Row row = iter.next();
				        String goods_sn = row.getCell(0).toString();
				        int goods_number = (int) row.getCell(2).getNumericCellValue();
				        BigDecimal goods_price = BigDecimal.valueOf(row.getCell(1).getNumericCellValue());
				        
				        List<Goods> goods = context.getGoodsRepository().findByGoodsSN(goods_sn);
				        if(!goods.isEmpty()){
				        	//根据添加的商品ID判断该商品是否已经在活动中
				        	SecKillGroupBuy current = context.getSecKillGroupBuyGoodsRepository().findCurrentSecKillGroupBuyByGoodsId(goods.get(0).getId(), new Date());
				    		SecKillGroupBuy unActivated = context.getSecKillGroupBuyGoodsRepository().findUnActivatedSecKillGroupBuyByGoodsId(goods.get(0).getId(), new Date());
				    			
				    		if(current == null && unActivated == null){
					        	List<SecKillGroupBuyGoods> goodsCheck = context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyIdAndGoodsId(secKillGroupBuyId, goods.get(0).getId());
					        	if(goodsCheck.isEmpty()){
					        		SecKillGroupBuyGoods skgbgoods = new SecKillGroupBuyGoods();
					        		skgbgoods.setSecKillGroupBuyId(secKillGroupBuyId);
					        		skgbgoods.setGoodsNumber(goods_number);
					        		skgbgoods.setGoodsPrice(goods_price);
					        		skgbgoods.setGoodsId(goods.get(0).getId());
									context.getSecKillGroupBuyGoodsRepository().save(skgbgoods);
					        	}
				    		}
				        }
				}
			}
		}
		
		return createModel("promotion/seckillgroupbuygoods/index")
				.add("seckillgroupbuygoodsPage",context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyId(secKillGroupBuyId, pageable))
				.add("viewState", "")
				.add("secKillGroupBuyId", secKillGroupBuyId);
	}
	
	
	@RequestMapping(value="deletegood",method= RequestMethod.POST)
	public BossModel deletegood(String viewState,long goodsId, int skgbid, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException{

		context.getSecKillGroupBuyGoodsRepository().deleteBySecKillGroupBuyIdAndGoodsId(skgbid, goodsId);
		
		GoodsSearch search;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState),"UTF-8")), GoodsSearch.class);
		}else{
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search),pageable);
		for (Goods good :goodsList) {
			List<SecKillGroupBuyGoods>skgbgood = context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyIdAndGoodsId(skgbid, good.getId());
			SecKillGroupBuy skgb = context.getSecKillGroupBuyRepository().findOne((long)skgbid);
			if(skgbgood.isEmpty()){
				good.setSeckillgroupbuy(0);
				good.setSeckillgroupbuyNumber(skgb.getSecKillGroupBuyNumber());
			}else{
				good.setSeckillgroupbuy(1);
				good.setSeckillgroupbuyPrice(skgbgood.get(0).getGoodsPrice());
				good.setSeckillgroupbuyNumber(skgbgood.get(0).getGoodsNumber());
			}
		}
		if(viewState != null && !viewState.trim().equals("")){
			return createModel("promotion/seckillgroupbuygoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("secKillGroupBuyId", skgbid)
					.add("viewState", viewState);
		}else{
			return createModel("promotion/seckillgroupbuygoods/goods_table").add("goodsPage",goodsList)
					.add("goodsSearch", search)
					.add("secKillGroupBuyId", skgbid)
					.add("viewState", "");
		}
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,int spid,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException{
		
		context.getSecKillGroupBuyGoodsRepository().delete(id);
		
		return createModel("promotion/seckillgroupbuygoods/seckillgroupbuygoods_table")
				.add("seckillgroupbuygoodsPage",context.getSecKillGroupBuyGoodsRepository().findBySecKillGroupBuyId(spid, pageable))
				.add("viewState", "")
				.add("secKillGroupBuyId", spid);

		
	}
}
